package com.util;

import java.sql.Connection;
import java.sql.SQLException;

import javax.sql.DataSource;

import com.mchange.v2.c3p0.ComboPooledDataSource;

public class JdbcUtils {

	private static DataSource dataSource = new ComboPooledDataSource();
	
	
	private static ThreadLocal<Connection> tl = new ThreadLocal<>();
	
	public static Connection getConnection(){
		Connection conn = tl.get();
		if(conn == null){
			try {
				conn = dataSource.getConnection();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			tl.set(conn);
		}
		return conn;
	}
	
	public static DataSource getDataSource(){
		return dataSource;
	}
	
	//开启事务
	public static void begin(){
		try {
			getConnection().setAutoCommit(false);
			
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
	}
	//回滚事务
	public static void rollback(){
		try {
			getConnection().rollback();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	//提交
	public static void commit(){
		try {
			getConnection().commit();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
